﻿using AutoUpdater.Models;
using AutoUpdater.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AutoUpdater
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private WebClient webClient;

        //Environment.CurrentDirectory
        public static string PACK_PATH_ALL = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + @"\appobd\update.zip";
        public static string PACK_DIR = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + @"\appobd\";

        //Create a Delegate that matches the Signature of the ProgressBar's SetValue method
        private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);

        private UpdateProgressBarDelegate updatePbDelegate;

        //private FileVersionInfo currentVersionInfo;
        private Version currentVersion;

        private String exeFile;

        public Action<double> UpdateProgressBarAction;

        public Action<string> ShowMsgAction;

        private VersionData remoteVersionData;
        public MainWindow()
        {
            InitializeComponent();
            progressBar.Minimum = 0;
            progressBar.Maximum = 100;
            ShowMsgAction = ShowMsg;
            UpdateProgressBarAction = UpdateProgressBar;
        }

        public void updateing()
        {
            progressBar.Value = 0;
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(100);
                UpdateProgressBar(i);
            }
        }

        private void UpdateProgressBar(double var)
        {
            this.progressBar.Value = var;
        }

        private void btnBegin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                btn.IsEnabled = false;
                btnCancel.IsEnabled = true;
                DoUpdate();
            }
            catch (Exception ex)
            {
                ShowMsgAction(ex.Message);
            }
            //updateing();
        }

        private void DoUpdate()
        {
            if (remoteVersionData != null)
            {
                Version new_version = Version.Parse(remoteVersionData.vcode);
                if (new_version > currentVersion)
                {
                    string url = string.Concat(remoteVersionData.apkurl);
                    ShowMsgAction("正在下载更新,请稍候...");
                    Download(url, PACK_PATH_ALL);
                }
                else
                {
                    btnBegin.IsEnabled = false;
                    btnCancel.IsEnabled = true;
                    ShowMsgAction("程序已是最新版本。");
                }
            }
            else
            {
                ShowMsgAction("未获取到版本信息。");
            }
        }

        private void carMove(int var)
        {
            DoubleAnimation dax = new DoubleAnimation();
            //DoubleAnimation day = new DoubleAnimation();
            //指定起点  
            //dax.From = 0;  
            //day.From = 0;  
            //指定终点  
            //Random rdm = new Random();  
            //dax.To = rdm.NextDouble() * 300;  
            //day.To = rdm.NextDouble() * 300;
            //dax.From = tt.X;
            //double index = dax.From.Value;

            double Width = progressBar.Width;
            double value = (Width * var / 100D) - tt.X;
            dax.By = value;
            //day.By = 100D;
            //指定时长  
            Duration duration = new Duration(TimeSpan.FromMilliseconds(30));
            dax.Duration = duration;
            //day.Duration = duration;
            this.tt.BeginAnimation(TranslateTransform.XProperty, dax);
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            webClient = new WebClient();
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Wc_DownloadFileCompleted);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            try
            {
                if (!Directory.Exists(PACK_DIR))
                {
                    Directory.CreateDirectory(PACK_DIR);
                }
                if (File.Exists(PACK_PATH_ALL))
                {
                    File.Delete(PACK_PATH_ALL);
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }

            string path = new DirectoryInfo(@"../").FullName;//当前应用程序路径的上级目录
            exeFile = path + Properties.Settings.Default.MainExe;
            if (!File.Exists(exeFile))
            {
                return;
            }
            FileVersionInfo currentVersionInfo = FileVersionInfo.GetVersionInfo(exeFile);
            currentVersion = Version.Parse(currentVersionInfo.ProductVersion);

            String response = GetDownloadPath();
            if (string.IsNullOrEmpty(response))
            {
                ShowMsgAction("获取版本信息失败,请稍后再试...");
                return;
            }

            BaseModel<VersionData> model = JsonConvert.DeserializeObject<BaseModel<VersionData>>(response);
            if ("OK".Equals(model.code))
            {
                remoteVersionData = model.result;
            }

            if (!String.IsNullOrEmpty(remoteVersionData.remarks))
            {
                String[] arr = remoteVersionData.remarks.Split(';');
                StringBuilder sb = new StringBuilder();
                foreach (var item in arr)
                {
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    sb.Append(Environment.NewLine);
                }
                this.textBox.Text = sb.ToString();
            }
            if (remoteVersionData != null)
            {
                ShowMsgAction("已获得新版本信息");
                Version current_version = Version.Parse(currentVersionInfo.ProductVersion);
                Version new_version = Version.Parse(remoteVersionData.vcode);
                if (new_version > current_version)
                {
                    this.btnBegin.IsEnabled = true;
                    this.btnCancel.IsEnabled = false;
                    if (Properties.Settings.Default.AutoUpdate)
                    {
                        string url = string.Concat(remoteVersionData.apkurl);
                        ShowMsgAction("正在下载更新,请稍候...");
                        Download(url, PACK_PATH_ALL);
                    }
                }
                else
                {
                    btnBegin.IsEnabled = false;
                    //btnCancel.IsEnabled = true;
                    ShowMsgAction("程序已是最新版本。");
                }
            }
            else
            {
                ShowMsgAction("未获取到版本信息。");
            }
        }

        private void ShowMsg(string msg)
        {
            this.labMessage.Content = msg;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (webClient != null)
            {
                webClient.CancelAsync();
                webClient.Dispose();//要加上这一句.
            }
        }

        /// <summary>  
        /// 下载更新  
        /// </summary>  
        public void Download(string url, string fileName)
        {
            this.btnBegin.IsEnabled = false;
            this.btnCancel.IsEnabled = true;
            try
            {
                if (webClient == null)
                {
                    webClient = new WebClient();
                    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Wc_DownloadFileCompleted);
                    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
                }
                webClient.DownloadFileAsync(new Uri(url), fileName);
            }
            catch (Exception ex)
            {
                this.btnBegin.IsEnabled = true;
                this.btnCancel.IsEnabled = false;
                ShowMsg(ex.Message);
            }
        }

        private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            UpdateProgressBarAction(e.ProgressPercentage);
            carMove(e.ProgressPercentage);
            ShowMsg(string.Format("正在下载文件，完成进度{0}%  {1}/{2}(字节)", e.ProgressPercentage, e.BytesReceived, e.TotalBytesToReceive));
        }

        private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    ShowMsg("连接超时或任务已取消...");
                }
                else
                {
                    if (e.Error == null)
                    {
                        //this.progressBar.Value = 100;
                        ShowMsg("下载完成,正在解压...");
                        if (!ZipHelper.UnZip(PACK_PATH_ALL))
                        {
                            ShowMsg("更新包解压失败...");
                            return;
                        }
                        ShowMsg("更新完成，正在为您重新打开【云领智库】");
                        using (Process process = new Process())
                        {
                            if (File.Exists(exeFile))
                            {
                                process.StartInfo.FileName = exeFile;
                                if (process.Start())
                                {
                                    System.Threading.Thread.Sleep(1000);
                                    Application.Current.Shutdown();
                                    return;
                                }
                            }
                        }
                        
                    }
                    else
                    {
                        ShowMsg(e.Error.Message);
                    }
                    this.progressBar.Value = 0;
                }

            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
            finally
            {
                this.btnBegin.IsEnabled = true;
                this.btnCancel.IsEnabled = false;
            }

        }

        /// <summary>
        /// 获取更新
        /// </summary>
        public string GetDownloadPath()
        {
            ShowMsgAction("正在检测更新,请稍候...");
            string response = string.Empty;
            string url = Properties.Settings.Default.GetDownloadPathUrl;

            try
            {
                HttpWebResponse respone = HttpWebResponseUtility.CreateGetHttpResponse(url, 6000, null, null);
                using (System.IO.StreamReader reader = new System.IO.StreamReader(respone.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                ShowMsg(e.Message);
            }
            return response;
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (webClient != null)
            {
                webClient.CancelAsync();
                webClient.Dispose();//要加上这一句.
            }
            e.Cancel = false;
        }

    }
}
